# coding=utf-8
import re
import logging
from django.conf import settings
from rest_framework.views import APIView
from rest_framework.response import Response
from django.shortcuts import redirect
from c21_qrcode.utils import viewutils
from c21_qrcode.common import common
from c21_qrcode import forms
from c21_qrcode.common.redis_service import SLurl
from c21_qrcode.common.auth import auth_check
from django.http import Http404


logger = logging.getLogger('error')


re_rule = re.compile(
    r'^(http|https)?://[a-zA-Z0-9-.]*/[rpsg]/(?P<short_url>[_a-zA-Z0-9-]*)')


class QRcode(APIView):
    '''
        获取二维码url
    '''

    @auth_check
    def get(self, request):
        form = forms.QRcodeForm(request.query_params)
        if not form.is_valid():
            return Response({'status': 400, 'msg': 'Params error'})
        data = data = form.cleaned_data
        long_url = data['long_url']
        icon = data.get('icon')
        need_icon = data.get('need_icon', 1)
        valid_time = data.get('valid_time')
        if not long_url:
            return Response({'status': 400, 'msg': 'Params error'})
        qrcode_info = viewutils.get_qrcode_info(
            long_url, str(self.appid), icon,
            need_icon=need_icon, ex=valid_time)
        if qrcode_info is False:
            error = '{0} {1}, long_url:{2}'.format(
                '短串生成器资源冲突', 'c21_qrcode_views', long_url)
            logger.error(error)
            return Response({
                'status': 500, 'msg': 'server error'})
        data = {
            'qrcode_url': qrcode_info['qrcode_url'],
            'short_url': qrcode_info['short_url']
        }
        context = {
            'status': 200,
            'msg': 'succeed',
            'data': data
        }
        return Response(context)


class UrlRender(APIView):
    '''
        短链跳转
    '''

    def get(self, request, short_url):
        slurl = SLurl()
        res = slurl.get(short_url)
        if not res:
            raise Http404('Not found')
        long_url = res['long_url']
        return redirect(long_url)


class LongUrl(APIView):
    '''
        由短连接获取长连接
    '''

    @auth_check
    def get(self, request):
        context = {
            'status': 400,
        }
        short_url = request.query_params.get('short_url', None)
        if not short_url:
            context['msg'] = u'we need short url'
            return Response(context)
        match = re.match(re_rule, short_url)
        slurl = SLurl()
        long_url = slurl.get(match.group('short_url'))['long_url']
        context['status'] = 200
        if not long_url:
            context['msg'] = u'not find'
            return Response(context)
        context['msg'] = u'succeed'
        context['data'] = {'long_url': long_url}
        return Response(context)


class ShortUrl(APIView):
    '''
        提供短连接服务
    '''

    @auth_check
    def post(self, request):
        long_url = request.data.get('long_url', None)
        if not long_url:
            context = {
                'status': 400,
                'msg': '参数错误'
            }
            return Response(context)
        short_url = common.only_short_url(
            long_url, pro=settings.URL_ED[self.appid])
        slurl = SLurl()
        value = {
            'icon_url': None,
            'qr_url': None,
            'long_url': long_url
        }
        slurl.set_only_key(short_url, value)
        short_url = settings.SHORT_URL_PREFIX[self.appid] + short_url
        context = {
            'status': 200,
            'msg': 'succeed',
            'data': {
                'short_url': short_url
            }
        }
        return Response(context)
